
package com.snail.mobile.sim.oss.userInfo.web.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.util.CollectionUtils;

import com.snail.mobile.sim.oss.userInfo.model.UserInfo;
import com.snail.mobile.sim.oss.userInfo.model.UserInfoResult;
import com.snail.mobile.sim.oss.userInfo.service.UserInfoManager;
import com.snail.mobile.sim.oss.userInfo.web.form.UserInfoForm;
import com.snail.mobile.sim.oss.util.Tools;
import com.sungrid.seine.oss.framework.service.BaseManager;
import com.sungrid.seine.oss.framework.util.PageList;
import com.sungrid.seine.oss.framework.util.StringHelper;
import com.sungrid.seine.oss.framework.web.action.BaseDispatchAction;

/**
 * Action class to handle CRUD on a UserInfo object
 *
 * @struts.action name="userInfoForm" path="/business/userInfo/userInfos" scope="request"
 *  validate="false" parameter="method"
 * @struts.action name="userInfoForm" path="/business/userInfo/deleteUserInfo" scope="request"
 *  validate="false" parameter="method"
  * @struts.action name="userInfoForm" path="/business/userInfo/editUserInfo" scope="request"
 *  validate="false" parameter="method"
 * @struts.action name="userInfoForm" path="/business/userInfo/saveUserInfo" scope="request"
 *  validate="true" parameter="method" input="edit"

 * @struts.action-forward name="edit" path="userInfo.form"
 * @struts.action-forward name="search" path="userInfo.list"
 * @struts.action-forward name="list" path="userInfos.do"  redirect="true"
 */
public final class UserInfoAction extends BaseDispatchAction
{

    public ActionForward cancelled(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception
    {
        return mapping.findForward("list");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("Entering 'delete' method");
        }

        ActionMessages messages = new ActionMessages();
        UserInfoForm userInfoForm = (UserInfoForm) form;

        // Exceptions are caught by ActionExceptionHandler
        UserInfoManager mgr = (UserInfoManager) getBean("userInfoManager");
        mgr.removeUserInfo(userInfoForm.getNid());

        messages.add(ActionMessages.GLOBAL_MESSAGE,
                     new ActionMessage("userInfo.deleted"));

        // save messages in session, so they'll survive the redirect
        saveMessages(request.getSession(), messages);

        return mapping.findForward("list");
    }

    public ActionForward edit(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("Entering 'edit' method");
        }

        UserInfoForm userInfoForm = (UserInfoForm) form;

        // if an id is passed in, look up the user - otherwise
        // don't do anything - user is doing an add
        if (userInfoForm.getNid() != null) {
            UserInfoManager mgr = (UserInfoManager) getBean("userInfoManager");
            UserInfo userInfo = mgr.getUserInfo(userInfoForm.getNid());
            userInfoForm = (UserInfoForm) convert(userInfo);
            updateFormBean(mapping, request, userInfoForm);
        }

        return mapping.findForward("edit");
    }

    public ActionForward save(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("Entering 'save' method");
        }

        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        UserInfoForm userInfoForm = (UserInfoForm) form;
      //  boolean isNew = ("".equals(userInfoForm.getNid()) || userInfoForm.getNid() == null);

       UserInfoManager mgr = (UserInfoManager) getBean("userInfoManager");

        UserInfo userInfo = null;

        BaseManager basemgr = (BaseManager)getBean("baseManager");
        //如果本地数据库没有，计费存在则添加
		String sphone = StringHelper.getQueryString(request, "sphone");
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserInfo.class);

		if (StringHelper.isNotNull(sphone)) {
			detachedCriteria.add(Expression.eq("sphone", sphone.trim()).ignoreCase());
		}
		List orders = new ArrayList();
		orders.add(Order.desc("nid"));
		List<UserInfo> userlst = basemgr.findList(detachedCriteria);
		
		UserInfoResult userInfoResult=mgr.getUserInfoFromBilling(Tools.getRemoteHost(request),sphone);
		
		
		
		if(CollectionUtils.isEmpty(userlst) && userInfoResult.getState().toString().equals("0")){
			   
	            messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("userInfo.added"));
	            saveMessages(request.getSession(), messages);
	            
	            
	            userInfo=new UserInfo();
	            
	            userInfo.setSphone(sphone);
	            userInfo.setDcreate(new  Timestamp(new Date().getTime()));
	            userInfo.setDupdate(new  Timestamp(new Date().getTime()));
	            userInfo.setSacc(sphone+"@SNAIL.COM");
	            
	        	mgr.saveUserInfo(userInfo);
		}else{
			 if(StringUtils.isNotEmpty(userInfoResult.getDesc())){
				 setSessionMessage(request, "本地数据库存在该账号或者"+userInfoResult.getDesc()+"。"+"不满足添加条件!");
			 }else{
				 setSessionMessage(request, "本地数据库存在该账号。"+"不满足添加条件!");
			 }
			
		}
        return mapping.findForward("list");
        
        
        
      /*  // add success messages
        if (isNew)
        {
            userInfo = (UserInfo) convert(userInfoForm);

            messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("userInfo.added"));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);
        } else
        {
            userInfo = mgr.getUserInfo(userInfoForm.getNid());
            copyProperties(userInfo, userInfoForm);

            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("userInfo.updated"));
            saveMessages(request, messages);
        }*/

        
    }

    public ActionForward search(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("Entering 'search' method");
        }

        // UserInfoForm userInfoForm = (UserInfoForm) form;
        // UserInfo userInfo = (UserInfo) convert(userInfoForm);
        String sphone= StringHelper.getQueryString(request, "sphone");
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserInfo.class);
		
		
		 if (StringHelper.isNotNull(sphone))
		    {

			 detachedCriteria.add(Expression.eq("sphone", sphone.trim()).ignoreCase());

		    }

		List orders = new ArrayList();

        orders.add(Order.desc("nid"));

        // UserInfoManager mgr = (UserInfoManager) getBean("userInfoManager");
        BaseManager mgr = (BaseManager)getBean("baseManager");

        PageList pageList = mgr.findPageList(detachedCriteria, getPage(request), orders);

        setPageList(request, pageList);

        return mapping.findForward("search");
    }

	public ActionForward onlinesearch(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'search' method");
		}

		// UserInfoForm userInfoForm = (UserInfoForm) form;
		// UserInfo userInfo = (UserInfo) convert(userInfoForm);
		String sphone = StringHelper.getQueryString(request, "sphone");
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserInfo.class);

		if (StringHelper.isNotNull(sphone)) {

			detachedCriteria.add(Expression.eq("sphone", sphone.trim()).ignoreCase());
			

		}

		detachedCriteria.add(Expression.isNotNull("scurCt"));
		detachedCriteria.add(Expression.ne("scurCt", ""));
		
		
		
		List orders = new ArrayList();

		orders.add(Order.desc("nid"));

		// UserInfoManager mgr = (UserInfoManager) getBean("userInfoManager");
		BaseManager mgr = (BaseManager) getBean("baseManager");

		PageList pageList = mgr.findPageList(detachedCriteria, getPage(request), orders);

		setPageList(request, pageList);
		
		request.setAttribute("online", "1");

		return mapping.findForward("search");
	}


    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
    throws Exception
    {
        return search(mapping, form, request, response);
    }
}